package com.pachiraframework.springcloud.user.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;

@Slf4j
@RestController
/**
 * 流在服务之间的流动，不是在用已有的API，之间下载
 * 而是用协议，用流的方式传递数据
 * 
 *	这种例子最好是做在个不同的服务之中，但我为了省事，也避免以后不好找，就都写在这里了
 */
@RequestMapping("/stream")
public class StreamController {
	@Autowired
    WebApplicationContext webApplicationContext;
	
	
	@Value("${server.port}")
    protected String port;
	
	
	
	/**
	 * 生产者接口，读取本地文件数据，并将数据已流的形式发送出去
	 * @param res
	 * @param name
	 * @throws IOException
	 */
	@RequestMapping(value= {"provider/{name}.xml"})
	@ResponseBody//一般说配置了@RestController，就ok了，但是如果不行就讲此@ResponseBody加入到此处
    //默认情况返回string会跳转到页面
	public void provider(HttpServletResponse res,@PathVariable(value="name") String name) throws IOException {
		ServletContext servletContext = webApplicationContext.getServletContext();
    	String realPath = servletContext.getRealPath("/");
    	
        String fileName = name+".xml";
        File file = new File(realPath + "user.xml");
        
        downloadFile(file,fileName,res);
        System.out.println("success");
		
		
    }
	public static void downloadFile(File file, String fileName,HttpServletResponse response) throws IOException {
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            fin = new FileInputStream(file);
            out = response.getOutputStream();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename="+fileName);

            byte[] buffer = new byte[1024];
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(fin != null) fin.close();
            if(out != null) out.close();

        }
    }
	
	
	
	/**
	 * 消费者接口，会调用生产者接口，并把文件转成流，放到浏览器中
	 * @param response
	 * @param name
	 * @throws IOException
	 */
	@RequestMapping(value= {"customer/{name}.xml"})
	@ResponseBody//一般说配置了@RestController，就ok了，但是如果不行就讲此@ResponseBody加入到此处
    //默认情况返回string会跳转到页面
	public void customer(HttpServletResponse response,@PathVariable(value="name") String name) throws IOException {
       
		CloseableHttpClient httpCilent = HttpClients.createDefault();//Creates CloseableHttpClient instance with default configuration.
        String fileName = name+".xml";
        HttpGet httpGet = new HttpGet("http://localhost:"+port+"/"+fileName);
        try {
            HttpResponse responses = httpCilent.execute(httpGet);

            InputStream fin = null;
            ServletOutputStream out = null;
            try {
                HttpEntity entity = responses.getEntity();
                fin = entity.getContent();
                out = response.getOutputStream();
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/x-download");
                response.addHeader("Content-Disposition", "attachment;filename="+fileName);

                byte[] buffer = new byte[1024];
                int bytesToRead = -1;
                // 通过循环将读入的Word文件的内容输出到浏览器中
                while((bytesToRead = fin.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesToRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(fin != null) fin.close();
                if(out != null) out.close();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpCilent.close();//释放资源
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		
		
    }
	
	
	
	
	
	
	
	

}
